/**
 * 病组结果分析--病组详情页面
 */
$(function(){
		
	var paramNewTab = $("#tabContent > .tab-pane.active").data();
	if(paramNewTab.tableType == "patientGroup"){//病组
		showDRGsDetail(paramNewTab);
	}else if(paramNewTab.tableType == "overproofPatientGroup"){//费用超标
		showOverproofDRGsDetail(paramNewTab);
	}
	$("#"+tabId+" #clinicDetail").hide();
	/////////////////////////////////////////////////////////////////////////
	//加载病组详情表格
	function showDRGsDetail(paramCase){
		var param = $.extend({}, paramCase);
		if(param.title){
			$("#"+tabId+" #disGroupList .ti").html(param.title);
		}
		var dateFrom = param.dateFrom , dateTo = param.dateTo;
		var thisYear  = dateFrom.substring(0,4) ? dateFrom.substring(0,4):'' ;
		var lastYear  = (dateFrom.substring(0,4)-1) ? (dateFrom.substring(0,4)-1)+"" : '' ;
		var thisDate = dateFrom  , lastDate = lastYear+dateFrom.substring(4);
		var dCode = param.depCode , wCode = param.wardCode , coverFlag = false ;
		//如果科室不为空并且病区为空，则 显示 “是否理论应治疗”字段
		(!wCode || 'hosp'== wCode || 'null' == wCode) && dCode && 'null' != dCode && (coverFlag = true) ;
		var patientGroupTitle = ['代码','描述','排序',''+lastYear,'排序',''+thisYear,''+lastYear,''+thisYear,''+lastYear,''+thisYear];
		var patientGroupDate = ['','','',lastDate,'',thisDate,lastDate,thisDate,lastDate,thisDate];
		var patientGroupListDiv = '<table id ="disGroupDetailTable"  class="table" width="98%" ><thead>'+
		' <tr>'+
		' <th colspan="2" style="text-align:center">DRG代码及描述</th>'+
		' <th colspan="4" style="text-align:center"><i class="icon-group" style="color: #007dbc;font-size: 14px;"></i>入组病例数</th>'+
		' <th colspan="2" style="text-align:center"><i class="glyphicon glyphicon-usd" style="color: #007dbc;font-size: 14px;"></i>次均费用</th>'+
		' <th colspan="2" style="text-align:center"><i class="fa fa-bed" style="color: #007dbc;font-size: 16px;"></i>平均住院日</th>'+
		' <th rowspan="2" style="vertical-align:middle" >权重</th>' ;
		if(coverFlag){
			patientGroupListDiv += ' <th rowspan="2" style="vertical-align:middle" >是否理论应治疗</th>';
		} 
		patientGroupListDiv += ' </tr><tr>'+
		' <th>'+patientGroupTitle[0]+'</th>'+
		' <th>'+patientGroupTitle[1]+'</th>'+
		' <th>'+patientGroupTitle[2]+'</th>'+
		' <th>'+patientGroupTitle[3]+'</th>'+
		' <th>'+patientGroupTitle[4]+'</th>'+
		' <th>'+patientGroupTitle[5]+'</th>'+
		' <th>'+patientGroupTitle[6]+'</th>'+
		' <th>'+patientGroupTitle[7]+'</th>'+
		' <th>'+patientGroupTitle[8]+'</th>'+
		' <th>'+patientGroupTitle[9]+'</th>'+
		' </tr>'+
		' </thead></table>';
		$("#"+tabId+" #disGroupListDiv").html(patientGroupListDiv);
		$.post(contextPath +"/DisGroupAnalysis/drgsDetail.dhc",param).done(function(result){
			var data = (result.data && result.data.length > 0 ) ? result.data : [];
			var columns=[
		                  	{"data": "DRGCODE"},
		                  	{"data": "DRGDESC"},
		                  	{"data": "LASTORDER"},
		                  	{"data": "LPCNT",
		 	            	   "render":function ( tdData, type, rowData, meta ) {
		 		            		 //tdData:当前cell的值（基于 columns.data）,rowData:整个row的数据, meta.row 行下标从0开始，meta.col 列下标从0开始
		 						    	//如果是过滤或者排序则返回原始数据
		 						    	if(type =='filter'||type =='sort'){
		 						    		return tdData;
		 						    	}
		 						    	return  tdData ? '<a dDesc="'+rowData.DRGDESC+'" dCode="'+rowData.DRGCODE+'" dYear="'+patientGroupDate[meta.col]+'" href="javascript:void(0)">'+tdData+'</a>' : tdData ;
		 		            	   }		                  	
		                  	} ,
		                  	{"data": "THISORDER"},
		                  	{"data": "TPCNT",
		 	            	   "render":function ( tdData, type, rowData, meta ) {
		 		            		 //tdData:当前cell的值（基于 columns.data）,rowData:整个row的数据, meta.row 行下标从0开始，meta.col 列下标从0开始
		 						    	//如果是过滤或者排序则返回原始数据
		 						    	if(type =='filter'||type =='sort'){
		 						    		return tdData;
		 						    	}
		 						    	return  tdData ? '<a dDesc="'+rowData.DRGDESC+'" dCode="'+rowData.DRGCODE+'" dYear="'+patientGroupDate[meta.col]+'" href="javascript:void(0)">'+tdData+'</a>' : tdData ;
		 		            	}
		                  	},
		                  	{"data": "LAVGFEE",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["LAVGFEE"],2) ;
			                     }
		                  	},
		                	{"data": "AVGFEE","width":"120px",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AVGFEE"],2) + "" + gridcompareValue(full["AVGFEE"],full["LAVGFEE"]) ;
			                     }
		                  	},
		                	{"data": "LAVGDAY",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["LAVGDAY"],2) ;
			                     }
		                  	},
		                	{"data": "AVGDAY","width":"100px",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AVGDAY"],2) + "" + gridcompareValue(full["AVGDAY"],full["LAVGDAY"]) ;
			                     }
		                  	},
		                	{"data": "WEIGHT"} 
		                 ];
			
			if(coverFlag){
				columns.push({
	            	   "data":"COVER",
	            	   "render":function ( tdData, type, rowData, meta ) {
	            		 //tdData:当前cell的值（基于 columns.data）      rowData:整个row的数据（不基于 columns.data）
					    	//如果是过滤或者排序则返回原始数据
					    	if(type =='filter'||type =='sort'){
					    		return tdData;
					    	}
					    	if( parseInt(tdData) == 1 ){
					    		return "是" ;
					    	}else{
					    		return "否" ;
					    	}
	            	   }					
				});
			}
			var paramsDataTables={
					searching:true,  //此选项用来开启、关闭Datatables的搜索功能
					lengthChange:true,  //是否允许最终用户改变表格每页显示的记录数
					ordering:true,  //是否允许Datatables开启排序
					"order": [[ 4, 'asc' ]],//默认第5列为升序排列
					stateSave:false, //状态保存 - 再次加载页面时还原表格状态
					info:false,  //控制是否显示表格左下角的信息
					scrollX:true, //显示水平滚动条
//					scrollY:'280px', //当表格高度超过280px的时候，显示垂直滚动条
					autoWidth:false, //控制Datatables是否自适应宽度
					orderCellsTop:true,
					tableTitle:"病组明细"
			};
			$("#"+tabId+" #disGroupDetailTable").dataTableBasic(columns,data,paramsDataTables);
	        //给超链接添加点击事件
	        $("#"+tabId+" #disGroupDetailTable tbody").on( 'click', '[href="javascript:void(0)"]', function () {
	        	showClinicGroup($(this),param,$(this).attr("dCode"),$(this).attr("dDesc"),$(this).attr("dYear"));	        			        	
	        } );
		});		
	}
	
	//加载费用超标病组详情表格
	function showOverproofDRGsDetail(paramCase){
		var param = $.extend({}, paramCase);
		if(param.title){
			$("#"+tabId+" #disGroupList .ti").html(param.title);
		}
		var dateFrom = param.dateFrom , dateTo = param.dateTo;
		var thisYear  = dateFrom.substring(0,4) ? dateFrom.substring(0,4):'' ;
		var lastYear  = (dateFrom.substring(0,4)-1) ? (dateFrom.substring(0,4)-1)+"" : '' ;
		var queryType = param.queryType;
		if(queryType=="last" || queryType=="thisNo"){
			thisYear = lastYear ;
		}else{
			$('#'+tabId+' .thisyear').html(dateFrom.substring(0,4));
		}
		var thisDate = thisYear+dateFrom.substring(4)  , lastDate = lastYear+dateFrom.substring(4);
		var dCode = param.depCode , wCode = param.wardCode , coverFlag = false ;
		//如果科室不为空并且病区为空，则 显示 “是否理论应治疗”字段
		(!wCode || 'hosp'== wCode || 'null' == wCode) && dCode && 'null' != dCode && (coverFlag = true) ;
		var patientGroupTitle = ['代码','描述','排序',''+thisYear,''+thisYear,'病组标杆',''+thisYear,'病组标杆'];		
		var patientGroupDate  = ['', '','',thisDate,'',thisDate,'',thisDate,''];
		var patientGroupListDiv = '<table id ="disGroupDetailTableOverProof"  class="table" width="98%" ><thead>'+
		' <tr>'+
		' <th colspan="2" style="text-align:center">DRG代码及描述</th>'+
		' <th colspan="2" style="text-align:center"><i class="icon-group" style="color: #007dbc;font-size: 14px;"></i>入组病例数</th>'+
		' <th colspan="2" style="text-align:center"><i class="glyphicon glyphicon-usd" style="color: #007dbc;font-size: 14px;"></i>次均费用</th>'+
		' <th colspan="2" style="text-align:center"><i class="fa fa-bed" style="color: #007dbc;font-size: 16px;"></i>平均住院日</th>'+
		' <th rowspan="2" style="vertical-align:middle">权重</th>';
		if(coverFlag){
			patientGroupListDiv += ' <th rowspan="2" style="vertical-align:middle" >是否理论应治疗</th>';
		} 
		patientGroupListDiv += ' </tr><tr>'+
		' <th>'+patientGroupTitle[0]+'</th>'+
		' <th>'+patientGroupTitle[1]+'</th>'+
		' <th>'+patientGroupTitle[2]+'</th>'+
		' <th>'+patientGroupTitle[3]+'</th>'+
		' <th>'+patientGroupTitle[4]+'</th>'+
		' <th>'+patientGroupTitle[5]+'</th>'+
		' <th>'+patientGroupTitle[6]+'</th>'+
		' <th>'+patientGroupTitle[7]+'</th>'+
		' </tr>'+
		' </thead></table>';
		$("#"+tabId+" #disGroupListDiv").html(patientGroupListDiv);		
		$.post(contextPath +"/DisGroupAnalysis/overproofDrgsDetail.dhc",param).done(function(result){
			var data = result.data ;
			var columns=[
		                  	{"data": "DRGCODE"},
		                  	{"data": "DRGDESC"},
		                  	{"data": "",
			               		"render":function(data,type,full,meta){
			               			return meta.row+1 ;
			               		}
			               	},
		                  	{"data": "INCASECNT",
		 	            	   "render":function ( tdData, type, rowData, meta ) {
		 		            		 //tdData:当前cell的值（基于 columns.data）,rowData:整个row的数据, meta.row 行下标从0开始，meta.col 列下标从0开始
		 						    	//如果是过滤或者排序则返回原始数据
		 						    	if(type =='filter'||type =='sort'){
		 						    		return tdData;
		 						    	}
		 						    	return  tdData ? '<a dDesc="'+rowData.DRGDESC+'" dCode="'+rowData.DRGCODE+'" dYear="'+patientGroupDate[meta.col]+'" href="javascript:void(0)">'+tdData+'</a>' : tdData ;
		 		            	   }	                  		
		                  	},
		                  	{"data": "AVGFEE",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AVGFEE"],2) ;
			                     }
		                  	},
		                	{"data": "AS_AVG_FEE","width":"120px",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AS_AVG_FEE"],2) ;
			                     }
		                  	},
		                	{"data": "AVGDAY",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AVGDAY"],2) ;
			                     }
		                  	},
		                	{"data": "AS_AVG_DAYS","width":"100px",
		                  		"render": function(obj, type, full) {
		                  			return formatNumber(full["AS_AVG_DAYS"],2) ;
			                     }
		                  	},
		                	{"data": "WEIGHT"} 
		                 ];
			if(coverFlag){
				columns.push({
	            	   "data":"COVER",
	            	   "render":function ( tdData, type, rowData, meta ) {
	            		 //tdData:当前cell的值（基于 columns.data）      rowData:整个row的数据（不基于 columns.data）
					    	//如果是过滤或者排序则返回原始数据
					    	if(type =='filter'||type =='sort'){
					    		return tdData;
					    	}
					    	if( parseInt(tdData) == 1 ){
					    		return "是" ;
					    	}else{
					    		return "否" ;
					    	}
	            	   }					
				});
			}
			var paramsDataTables={
					searching:true,  //此选项用来开启、关闭Datatables的搜索功能
					lengthChange:true,  //是否允许最终用户改变表格每页显示的记录数
					ordering:true,  //是否允许Datatables开启排序
					"order": [[ 3, 'desc' ]],//默认第4列为降序排列
					stateSave:false, //状态保存 - 再次加载页面时还原表格状态
					info:false,  //控制是否显示表格左下角的信息
					scrollX:true, //显示水平滚动条
					scrollY:false, //显示垂直滚动条
					autoWidth:false, //控制Datatables是否自适应宽度
					orderCellsTop:true,
					tableTitle:"费用超标病组明细"
			};
			$("#"+tabId+" #disGroupDetailTableOverProof").dataTableBasic(columns,data,paramsDataTables);
	        //给超链接添加点击事件
	        $("#"+tabId+" #disGroupDetailTableOverProof tbody").on( 'click', '[href="javascript:void(0)"]', function () {
	        	showClinicGroup($(this),param,$(this).attr("dCode"),$(this).attr("dDesc"),$(this).attr("dYear"));	        			        	
	        	return false;
	        } );
		});		
	}
	//主诊组信息弹出框--病组
	function showClinicGroup(obj,paramCase,drgCode,drgDesc,checkYear,overProof){
		var param = $.extend({}, paramCase);
		if(!drgCode || !checkYear ) return false;
		$("#"+tabId+" #clinicDetail").show();
		$("#"+tabId+" #clinicDetail .ti").html(drgCode+' 主诊组详情');
		var showTitle = checkYear.length >= 4 ?checkYear.substring(0,4)+'年':'';
		showTitle += checkYear.length >= 7 ?checkYear.substring(5)+'月':'';
		var clinicGroupDiv =  $("#"+tabId+" #clinicDetailDiv").html(''
			+' <div class="row-fluid clearfix">  '
			+' 		<div class="col-sm-6">  '
			+'			<div id="clinicPie" ></div>'
			+' 		</div>'
			+' 		<div class="col-sm-6">  '
			+			'<h4 align="center">'+showTitle+'主诊组指标明细表</h4>'
		 	+			'<table id="clinicTable1" class="table table-bordered table-hover">'
		 	+			'	<thead>'
		 	+			'		<tr>'
		 	+			'			<th>主诊组</th>'
		 	+			'			<th><label><i class="icon-group" style="color: #007dbc;font-size: 14px;"></i>入组病例数</label></th>'
		 	+			'			<th><span><i class="glyphicon glyphicon-usd" style="color: #007dbc;font-size: 14px;"></i>次均费用(元)</span></th>'
		 	+			'			<th><div><i class="fa fa-bed" style="color: #007dbc;font-size: 16px;"></i>平均住院日</div></th>'
		 	+			'		</tr>'
		 	+			'	</thead>'
		 	+			'</table>'
		 	+           '<div class="zhujie">'
		 	+			'</div>'
			+' 		</div>'
			+' </div>'				
		);
		param.drgCode = drgCode;
		param.yearFromA = checkYear;
		//如果是费用超标病组 则将 param.monitorType = 'overproof'
		overProof && ( param.monitorType = overProof );

		$.post(contextPath +"/DisGroupAnalysis/clinicGroupList.dhc",param).done(function(result){
	    	var tableData = result.data ? result.data:[];
	    	var pagingFlag = (tableData && tableData.length >10 )? true : false ;
	    	//表格信息 	
			var paramsDataTables={
				searching: false, //此选项用来开启、关闭Datatables的搜索功能
				lengthChange: false, //是否允许最终用户改变表格每页显示的记录数
				paging: pagingFlag,  //是否开启本地分页
				info:false,     //控制是否显示表格左下角的信息
				ordering:true,  //是否允许Datatables开启排序
				"order": [[ 1, 'desc' ]],//默认第2列为降序排列
				autoWidth:true, //控制Datatables是否自适应宽度
				exportEnable:false,//是否可导出
//				scrollY: "210px",//当表格高度超过300px的时候，显示垂直滚动条
				drawCallback:function( oSettings ) { //table加载完成后回调事件
					var pieData = [];//饼图数据
					console.log(oSettings);
					if(oSettings.aoData && oSettings.aoData.length > 0){
						var start = oSettings._iDisplayStart+oSettings._iDisplayLength;
						var end = oSettings._iDisplayStart;
						for(var i=start-1;i>=end;i--){
							var row = oSettings.aoData[i];
							if(typeof(row) != "undefined")
							{
								rowData = row._aData;
								pieData.push({name:rowData.GROUP_NAME,value:rowData.PATIENTNUM});
							}
						}									
					}
					var chartParams = { 'center' : ['40%','50%'] ,//饼图的中心（圆心）坐标，数组的第一项是横坐标，第二项是纵坐标,设置成百分比时第一项是相对于容器宽度，第二项是相对于容器高度
							'legendPosition' : 'bottom',//图例组件离容器上侧top,下侧bottom,左侧 left,右侧right的距离
							//特殊的值有  left 的值有'left', 'center', 'right' , top 的值有'top', 'middle', 'bottom' , right 和 bottom 没有前面类似字符串的值,只有下面的数据样式的值
							'legendPositionVal' : '10',//与上面对应的数值 可以是像 20 这样的具体像素值，可以是像 '20%' 这样相对于容器高宽的百分比
//							'pagemode' : true ,
							'radius':[0, '50%'] //饼图的半径，数组的第一项是内半径，第二项是外半径
					};
					var pieHeight = parseInt(clinicGroupDiv.find("#clinicTable1").height())+90;
					clinicGroupDiv.find("#clinicPie").height( pieHeight < 280 ? 280: pieHeight );
					pieCharts(clinicGroupDiv.find("#clinicPie"), pieData, '病例分布图', drgCode+'--'+drgDesc, chartParams);
		        }
			};
			var columns=[
	               {"data":"GROUP_NAME"},
	               {"data":"PATIENTNUM",
	            	   "render":function ( tdData, type, rowData, meta ) {
		            		 //tdData:当前cell的值（基于 columns.data）      rowData:整个row的数据（不基于 columns.data）
		            		   return '<a infoCode="'+rowData.GROUPCODE+'" infoYear="'+checkYear+'" infoDrgCode="'+drgCode+'" href="javascript:void(0)">'+tdData+'</a>';
		                }
	               },
	               {"data":"AVGFEE",
                 		"render": function(tdData, type, rowData) {
                  			return formatNumber(tdData,2) ;
	                     }
	               },
	               {"data":"AVGDAYS"}
		     ];
			//将导出按钮的全局变量值保存起来
			var exportEnable_rules = window.exportEnable;
			//将全局公共button变量值保存起来
			var buttonsCommon_rules = window.buttonsCommon;
			//设置导出按钮为false
			window.exportEnable=false;
			//如果没有导出权限，则将定义的公共button清空
			window.buttonsCommon=[];
			//绘制表格
			clinicGroupDiv.find("#clinicTable1").dataTableBasic(columns, tableData,paramsDataTables);						
			//恢复导出按钮的全局变量值
			window.exportEnable= exportEnable_rules;
			//恢复全局公共button变量值
			window.buttonsCommon= buttonsCommon_rules;
			
			//写注释
			var tableTextData = result.data ? result.data:[];
			if(tableTextData && tableTextData[0]){
				var textData = tableTextData[0] ;
				var showTitleAnalysis ='<div>注: ';
				showTitleAnalysis += drgCode+'病组指标标杆值如下：</div>';
				showTitleAnalysis += '<div>次均费用：<label>'+(textData.AS_AVG_FEE ? formatNumber(textData.AS_AVG_FEE,2):'0')+'</label>元</div>';
				showTitleAnalysis += '<div>平均住院日：<label>'+(textData.AS_AVG_DAYS ? formatNumber(textData.AS_AVG_DAYS,2) :'0')+'</label>天</div>';
				clinicGroupDiv.find(".zhujie").html(showTitleAnalysis);
			}
	        //给入组病例数添加点击事件
			clinicGroupDiv.find("#clinicTable1 tbody").on( 'click', '[href="javascript:void(0)"]', function () {        			        	
	        	//这里参数是传地址的，如果用 var paramCase = param，则会改变param里面的值
				var paramCase = $.extend({}, param);
	        	paramCase.monitorType = $(this).attr("infoCode");
	        	paramCase.dateFrom = checkYear;
	        	paramCase.dateTo = checkYear;
	        	$.post(contextPath+'/DisGroupAnalysis/loadClinicCase.dhc',paramCase).done(function(result){
	        		if(depCode){
	        			depCode = depCode.replace(/,/g, '');
	        		}
	        		openTab('/pages/yizheng/fenxi/caselist.jsp', '病例明细',$(this).attr("infoCode")+drgCode+checkYear+"linicCaseList",$(this).attr("infoCode")+drgCode+checkYear+"linicCaseList",{param:paramCase, data:result.data});
	        	});
	        } );
			
			if(obj){
				var mao = $("#"+tabId+" #clinicDetailDiv");
                var pos = mao.offset().top;
                var poshigh = (mao.height())/2;
                $("html,body").animate({ scrollTop: pos-poshigh }, 1000);
			}
			
		});
	}//

	
})